<!-- 新建实物奖品 -->
<template>
  <a-drawer
    v-model:visible="vdata.visible" 
    :maskClosable="false"
    :body-style="{ paddingBottom: '80px' }" 
    width="40%"
    class="drawer-width" 
    @close="onClose"
  >
    <template #title>
      <div style="display:flex;justify-content:space-between;align-items:center;">
        <span v-if="vdata.isAdd">新增实物奖品</span>
        <span v-else>{{ vdata.disabled ? '追加' : '修改' }}实物奖品</span>
        <!-- 只有新增和草稿状态下 有保存草稿的功能 -->
        <a-button :disabled="vdata.disabled" @click="onSaveDraft">保存草稿</a-button>
      </div>
    </template>

    <Step :current-step="vdata.currentStep" :steps="stepsConfig" />

    <a-form
      v-if="vdata.currentStep == 0"
      ref="stepForm0Ref"
      :model="vdata.baseObject"
      layout="vertical"
      :wrapperCol="{span: 24}"
      labelAlign="left"
      :hideRequiredMark="false"
      :rules="vdata.step0Rules"
      :scrollToFirstError="true"
      style="margin-top: 20px;"
    >
      <a-row type="flex" justify="space-between" wrap="true">
        <a-col :span="11">
          <a-form-item label="机构" name="agentNo">
            <GzTreeSelect ref="gzThreeRef" v-model:value="vdata.baseObject['agentNo']" :disabled="!vdata.isAdd" />
          </a-form-item>
        </a-col>
        <a-col :span="11">
          <a-form-item label="奖品名称" name="goodsName">
            <a-input v-model:value="vdata.baseObject['goodsName']" placeholder="请输入奖品名称" :disabled="vdata.disabled" :maxlength="16" />
          </a-form-item>
        </a-col>
        <a-col :span="11">
          <a-form-item label="奖品数量" name="goodsNum">
            <a-input-number
              v-model:value="vdata.baseObject['goodsNum']"
              :min="vdata.minGoodsNum"
              :precision="0"
              placeholder="请输入奖品数量"
              :disabled="vdata.disabled"
              style="width: 100%"
            />
          </a-form-item>
        </a-col>
        <a-col :span="11">
          <a-form-item label="单价（元）" name="goodsPrice">
            <a-input-number
              v-model:value="vdata.baseObject['goodsPrice']"
              :disabled="vdata.disabled"
              style="width: 100%"
              :min="0"
              :precision="2"
              placeholder="请输入单价"
            />
          </a-form-item>
        </a-col>
        <a-col :span="11">
          <a-form-item label="预算金额（元）" name="goodsAmount">
            <a-input-number
              v-model:value="vdata.baseObject['goodsAmount']"
              disabled
              style="width: 100%"
              min="0"
              :precision="2"
              placeholder="0"
            />
          </a-form-item>
        </a-col>
        <a-col :span="11">
          <a-form-item label="奖品sku" name="goodsSku">
            <a-input v-model:value="vdata.baseObject['goodsSku']" placeholder="请输入奖品sku" :disabled="vdata.disabled" />
          </a-form-item>
        </a-col>
        <a-col :span="11">
          <a-form-item label="奖品领取（兑换）过期时间" name="goodsOverTime">
            <a-date-picker
              v-model:value="vdata.baseObject['goodsOverTime']"
              :disabled="vdata.disabled"
              style="width: 100%"
              value-format="YYYY-MM-DD [23:59:59]"
              :disabledDate="(current)=>current && current < dayjs().endOf('day')"
              placeholder="奖品领取（兑换）过期时间"
            />
          </a-form-item>
        </a-col>
        <a-col :span="11">
          <a-form-item label="奖品领取有效天数" name="goodsOverDays">
            <a-input-number
              v-model:value="vdata.baseObject['goodsOverDays']"
              :disabled="vdata.disabled"
              style="width: 100%"
              :min="1"
              :precision="0"
              placeholder="奖品领取有效天数"
            />
          </a-form-item>
        </a-col>
 

        <a-col v-if="vdata.baseObject['scoreOverType'] === 1" :span="11">
          <a-form-item label="过期时间" name="scoreOverTime">
            <a-date-picker
              v-model:value="vdata.baseObject['scoreOverTime']"
              :disabled="vdata.disabled"
              valueFormat="YYYY-MM-DD"
              :disabled-date="
                (current) => current && current < dayjs().endOf('day')
              "
              style="width: 100%"
            />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="备注" name="remark">
            <a-textarea
              v-model:value="vdata.baseObject['remark']"
              :disabled="vdata.disabled"
              placeholder="请输入备注"
              :rows="4"
            />
            <span class="gz-tip-text">换行符：\n</span>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="商品图片--列表小图（1:1）" name="goodsImgListSmall">
            <GzUpload v-model:src="vdata.baseObject['goodsImgListSmall']" bizType="activity" :disabled="vdata.disabled" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="商品图片--列表大图（16:9）" name="goodsImgListBig">
            <GzUpload v-model:src="vdata.baseObject['goodsImgListBig']" bizType="activity" :disabled="vdata.disabled" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="商品图片--banner (最多3个)" name="goodsImgBanner">
            <div v-for="(src,index) in vdata.baseObject['goodsImgBanner']" :key="index" class="img-list">
              <div class="img-item">
                <a-image class="img" :src="src" />
                <a :href="src">{{ getFileName(src) }}</a>
                <delete-outlined class="cp" :style="{ cursor: vdata.disabled ? 'not-allowed' : 'pointer' }" @click="!vdata.disabled && imgDelete('goodsImgBanner',index)" />
              </div>
            </div>
            <GzUpload v-if="vdata.baseObject['goodsImgBanner'].length < 3" :showUploadList="false" bizType="activity" :disabled="vdata.disabled" @change="(formReqFileUrl) => uploadChange(formReqFileUrl,'goodsImgBanner')" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="商品详情(富文本)" name="goodsDetail">
            <a-textarea
              v-model:value="vdata.baseObject['goodsDetail']"
              :disabled="vdata.disabled"
              placeholder="请输入商品详情(富文本)"
              :rows="4"
            />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>

    <Setting
      v-if="vdata.currentStep==1"
      ref="stepForm1Ref"
      :awardSettingId="awardSettingId"
      :disabled="vdata.disabled"
      :isDisabled="vdata.disabled|| vdata.isDisabled"
      :isDetail="vdata.isDetail"
      @sendData="handleChildrenData"
    />
    <MerchantFrom
      v-if="vdata.currentStep == 2"
      ref="stepForm2Ref"
      :awardId="vdata.baseObject.couponId"
      :awardType="awardType"
      :isDetail="vdata.isDetail"
      :isDisabled="vdata.disabled||vdata.isDisabled"
    />
    <PersonnelFrom
      v-if="vdata.currentStep == 3"
      ref="stepForm3Ref"
      :awardId="vdata.baseObject.couponId"
      :awardType="awardType"
      :isEmployee="vdata.baseObject.isEmployee"
      :isDisabled="vdata.disabled|| vdata.isDisabled"
      :isDetail="vdata.isDetail"
    />
    <InstitutionFrom
      v-if="vdata.currentStep == 4"
      ref="stepForm4Ref"
      :awardId="vdata.baseObject.couponId"
      :awardType="awardType"
      :isAllocation="vdata.baseObject.isAllocation"
      :agentNo="vdata.baseObject.agentNo"
      :isDisabled="vdata.disabled || vdata.isDisabled"  
      :isPush="vdata.disabled"
      :isDetail="vdata.isDetail"
    />
    <div class="drawer-btn-center">
      <a-button v-if="vdata.currentStep != 0" style="margin-right:8px" @click="onSteps(-1)">
        <step-backward-outlined />
        上一步
      </a-button>
      <a-button v-if="vdata.currentStep != 4" :loading="vdata.btnLoading" style="margin-right:8px" @click="onSteps(1)">
        <step-forward-outlined />
        下一步
      </a-button>
      <a-button
        v-if="vdata.currentStep == 4"
        type="primary"
        :loading="vdata.btnLoading"
        @click="onSave(false)"
      >
        <check-outlined />
        保存
      </a-button>
    </div>
  </a-drawer>
</template>

<script lang="ts" setup>
import { $goodsDetail, $goodsState,$goodsAddOrEdit} from '@/api/awardMange/goods/index'
import{$addStting,$updateStting}from '@/api/awardMange/coupon/index'

import { reactive, ref, getCurrentInstance, watch } from 'vue'
import numberUtil from '@/utils/numberUtil.js'
import dayjs from 'dayjs'
import Step from '../components/step/index.vue'
import Setting from '../components/setting/index.vue'
 import PersonnelFrom from '../components/PersonnelFrom/index.vue'
 import MerchantFrom from '../components/MerchantFrom/index.vue'
import InstitutionFrom from '../components/InstitutionFrom/index.vue'

const { $infoBox } = getCurrentInstance()!.appContext.config.globalProperties
// 获取当前实例的代理对象
const { proxy }: any = getCurrentInstance()
// 步骤配置
const stepsConfig = ref([
  { title: '实物基本信息' },
  { title: '实物配置信息' },
  { title: '可核销商户' },
  { title: '可派发人员' },
  { title: '实物数量配置' }
])

const props = defineProps(['callbackFunc']) 
const awardType = ref(1)
const stepForm1Ref = ref()
const stepForm2Ref = ref()
const stepForm3Ref = ref()
const stepForm4Ref = ref()
const vdata: any = reactive({
  btnLoading: false,
  currentStep: 0,
  isAdd: true, // 新增 or 修改页面标志
  baseObject: {
  }, // 数据对象
  visible: false, // 是否显示弹层/抽屉
  minGoodsNum: 1,  // 卡券张数限制 卡券在配置中状态时 卡券张数只可增加不能减少
  disabled: false,  // 在下架修改时 只允许修改卡券数量 且只能增加不能减少
  step0Rules: {
    goodsName: [{ required: true, message: '奖品名称不能为空', trigger: 'blur' },],
    goodsPrice: [{ required: true, message: '奖品价值不能为空', trigger: 'blur' },],
    goodsNum: [{ required: true, message: '奖品数量不能为空', trigger: 'blur' },],
    goodsSku: [{ required: true, message: '奖品sku不能为空', trigger: 'blur' },],
    goodsOverDays: [{ required: true, message: '奖品领取有效天数不能为空', trigger: 'blur' },],
    verifiedScore: [{ required: true, message: '核销后奖励福分不能为空', trigger: 'blur' },],
    scoreOverType: [{ required: true, message: '福分过期规则类型不能为空', trigger: 'blur' },],
    scoreOverDays: [{ required: true, message: '有效天数不能为空', trigger: 'blur' },],
    scoreOverTime: [{ required: true, message: '过期时间不能为空', trigger: 'blur' },],
    agentNo: [{ required: true, message: '请选择机构', trigger: 'blur' },],
    isLimitUser:[ { required: true, trigger: 'blur', message: '发放限制不能为空',} ],
    limitUserContent:[{required: true, message: '请选择发放客户等级限制', trigger: 'blur'}],
    isOpenReceipt:[ { required: true, trigger: 'blur', message: '回执不能为空',} ],
    goodsImgListSmall: [{ required: true, trigger: 'blur', message: '请上传商品列表图' },],
    goodsImgListBig: [{ required: true, trigger: 'blur', message: '请上传商品列表图' },],
    goodsImgBanner: [{ required: true, trigger: 'blur', validator:()=>imgValidator('goodsImgBanner','请上传主图') },],
    goodsDetail: [{ required: true, trigger: 'blur', message: '请输入商品详情' },]
  },

})

// 图片上传字段验证
function imgValidator(type,message){
  if(vdata.baseObject[type].length === 0){
    return Promise.reject(message)
  }else{
    return Promise.resolve()
  }
}
// 图片上传事件 formReqFileUrl为上传的图片地址,type为主图和详情图的字段
function uploadChange(formReqFileUrl,type){
  vdata.baseObject[type].push(formReqFileUrl)
}
// 根据图片地址返回图片名称
function getFileName(src){
  if(!src){
    return src
  }
  return src.substring(src.lastIndexOf('/') + 1)
}
// 删除图片
function imgDelete(type,index){
  vdata.baseObject[type].splice(index,1)
}
/**
 * 监听卡券张数和面额 自动计算卡券预算
 */
 watch([() => vdata.baseObject.goodsNum, () => vdata.baseObject.goodsPrice],(newVal, oldVal) =>{
  if(oldVal[0] === undefined && oldVal[1] === undefined) return
  if(vdata.baseObject.goodsNum && vdata.baseObject.goodsPrice){
    vdata.baseObject.goodsAmount = numberUtil.computeNumber(vdata.baseObject.goodsNum, '*', vdata.baseObject.goodsPrice).result
  }
},{ immediate: false })

/**
 * 切换步骤
 */
function onSteps(step: number) {
  if (step < 0) {
    vdata.currentStep--
  } else {
    if(vdata.isDetail){
      vdata.currentStep++
    }else{
      proxy.$refs['stepForm' + vdata.currentStep + 'Ref'].validate().then(() => {
      // 第一步网络请求 奖品信息
      if(vdata.currentStep === 0){
        step0Request(false)
      }else if(vdata.currentStep===1){
          saveStting()  
        }  else if (vdata.currentStep === 2 || vdata.currentStep === 3) {
          // 第二步 上传可核销商户清单
          if(vdata.currentStep === 3){
          // 调用员工组件暴漏的 handleIsEmployeeChange
          proxy.$refs['stepForm3Ref'].handleIsEmployeeChange()
          }
          vdata.currentStep++
        }

    }).catch((err)=>{console.log(err)})
    }
    
  }
}
/**
 * 第一步网络请求 卡券信息
 */
function step0Request(isDraft: boolean, showMsg: boolean = false) {
  const uploadObject = JSON.parse(JSON.stringify(vdata.baseObject))
  const { goodsImgBanner, goodsPrice, goodsAmount, goodsId } = uploadObject
  // 请求方法
  const method = goodsId ? 'PUT' : 'POST'
  uploadObject.goodsImgBanner = goodsImgBanner.join()
  if(goodsPrice){
    uploadObject.goodsPrice = numberUtil.computeNumber(goodsPrice, '*', 100).result
  }
  if(goodsAmount){
    uploadObject.goodsAmount = numberUtil.computeNumber(goodsAmount, '*', 100).result
  }
  // 删除冗余数据
  delete uploadObject.awardMchList
  $goodsAddOrEdit(method,uploadObject).then((res)=>{
    if(method === 'POST'){  // 新增时需要拿到卡券id 和awardSettingId
      couponIdOne.value = res.goodsId
    // 新增的时候不会走setting里面的暴漏处来的handleChildrenData这个方法所以拿不到 couponId
      vdata.baseObject.couponId = res.goodsId
      vdata.baseObject.goodsId = res.goodsId
    }
    if(isDraft){
      if(showMsg){
        $infoBox.message.success('保存成功')
        onClose()
      }
      return
    }
    vdata.currentStep++
  })
}

const  couponIdOne = ref()
const couponIdUpdate = ref()
const  baseObjectSetting = ref()

// 接受子组件传递过来的基本信息限制配置的对象 
 function handleChildrenData(childrenObject:any){  
  baseObjectSetting.value = childrenObject.childrenbaseObject
  if(vdata.isAdd){
    vdata.baseObject.couponId = couponIdOne.value
  }else{
    vdata.baseObject.couponId = couponIdUpdate.value
  }
  
 }


// 通过awardSettingId来查配置的详情
// 第二部网络请求
const awardSettingId = ref()
function saveStting(){  
   const uploadObject =  proxy.$refs['stepForm1Ref'].changehadleSaveStting()
    uploadObject.awardId =  vdata.baseObject.couponId
     uploadObject.awardType = awardType.value      
  if(awardSettingId.value||uploadObject.awardSettingId){
  uploadObject.awardSettingId =  awardSettingId.value?awardSettingId.value:uploadObject.awardSettingId
  $updateStting(uploadObject).then((res) => { 
       vdata.currentStep++
  })
  }else{
  $addStting(uploadObject).then((res) => {      
      awardSettingId.value = res
    vdata.currentStep++
  })
  }

}


/**
 * 最后的保存
 */
function onSave(isDraft: boolean) {
  if(vdata.isDetail){
    onClose()
  }else{
    proxy.$refs['stepForm4Ref'].handleIsAllocationChange()
  const  goodsId  = vdata.baseObject.couponId
  const state = isDraft ? 0 : 2
  $goodsState( { goodsId, state }).then(() => {
    $infoBox.message.success('保存成功')
    onClose()
  })
  }
   
}

/**
 * 保存草稿
 */
function onSaveDraft(){
  if(vdata.currentStep == 0){ // 在第一步 保存草稿
    // 移除校验结果
    clearFieldValidate()
    proxy.$refs['stepForm' + vdata.currentStep + 'Ref'].validate(['agentNo','goodsName']).then(() => {  // 草稿只验证商品名称
      step0Request(true,true)
    }).catch(()=>{})
  }else if (vdata.currentStep === 1) {
      saveStting()
    // 第二步 保存草稿
    onClose()
  } else if(vdata.currentStep==2) {
    $infoBox.message.success('保存成功')
    onClose()
  }else if(vdata.currentStep==3){
     proxy.$refs['stepForm3Ref'].handleIsEmployeeChange()
      $infoBox.message.success('保存成功')
    onClose()
  }else{
     proxy.$refs['stepForm4Ref'].handleIsAllocationChange()
      $infoBox.message.success('保存成功')
     onClose()

  }
}

/**
 * 弹出层打开事件
 * @param goodsId 实物奖品ID
 */
 function show(goodsId,disabled,isDisabled,isDetail,minGoodsNum) {
  vdata.isAdd = !goodsId
  vdata.btnLoading = false
  vdata.goodsId = goodsId

  vdata.currentStep = 0
   awardSettingId.value = null
  // 移除校验结果
  clearFieldValidate()
  // 重置表单数据
  vdata.baseObject = {
    everyonePeriodType: 0,
    isLimitUser:0,
    isOpenReceipt:0,
    receiptContent: {},
    verifiedScore: 0,
    goodsImgBanner: [],
    isAllocation: 0,
  }
  vdata.minGoodsNum = minGoodsNum
  // 判断是详情的话，直接禁用
  vdata.disabled = disabled
  vdata.isDisabled = isDisabled
  
  // 判断点击的是详情，点击保存不调用接口
  vdata.isDetail = isDetail
  if(vdata.isAdd){  // 新增
    vdata.visible = true
  }else{
    $goodsDetail({goodsId}).then((res)=>{
      // 深拷贝 coupon 对象以便修改
      vdata.baseObject = {
        ...res,
        goodsImgBanner: res.goodsImgBanner ? res.goodsImgBanner.split(',') : [],
        goodsPrice: numberUtil.computeNumber(res.goodsPrice, '/', 100).result,
        goodsAmount: numberUtil.computeNumber(res.goodsAmount, '/', 100).result,
        awardAgentList:res.awardAgentList,
        isAllocation:res.awardSetting?.isAllocation,
        isEmployee:res.awardSetting?.isAllocationUser

      }
       couponIdUpdate.value = res.goodsId
      if(res.awardSetting){
        //  修改的时候拿到settingid去查setting信息
         awardSettingId.value = res.awardSetting.awardSettingId
        }
      
      vdata.visible = true
    })
  }
}

/**
 * 清除表单字段验证
 */
function clearFieldValidate(){
  if (proxy.$refs['stepForm' + vdata.currentStep + 'Ref'] != undefined) {
    proxy.$refs['stepForm' + vdata.currentStep + 'Ref'].clearValidate() // 清除验证
  }
}
/**
 * 关闭弹层
 */
function onClose() {
  if(vdata.isDetail){
    vdata.baseObject.agentNo = '' // 关闭弹层时清空选择机构 以再重新打开时触发机构树请求
  vdata.visible = false
  }else{
    props.callbackFunc()
  vdata.baseObject.agentNo = '' // 关闭弹层时清空选择机构 以再重新打开时触发机构树请求
  vdata.visible = false
  }
 
}
/**
 * 暴露接口
 */
defineExpose({
  show
})

</script>
<style lang="less" scoped>
.margin-left {
  margin-left: 10px;
}
.mt10 {
  margin-top: 10px;
}
.mb0{
  margin-bottom: 0;
}

.a-radio {
  line-height: 40px;
}

.tag {
  position: absolute;
  right: -20px;
  top: 8px;
}

.remark {
  color: #999999;
}
.img-list{
  display: flex;
  margin-top: 10px;
  width: 100%;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  padding: 8px;
  .img-item{
    width: 100%;
    display: flex;
    justify-content: flex-start;
    align-items: center;
    gap: 8px;
    a{
      flex-grow: 1;
    }
    :deep(img){
      width: 48px;
      height: 48px;
      object-fit: cover;
    }
  }
}
:deep(.ant-space .ant-space-item:nth-of-type(2)){
  flex-grow: 1;
}
</style>
